/**
 * @Author       : oak-c
 * @Date         : 2021-01-21 15:02:20
 * @Description  : 短信
 * @LastEditors  : oak-c
 * @LastEditTime : 2021-01-21 15:40:55
 * @FilePath     : /src/service/sms/sms.service.ts
 */
import { SmsRecordRepo } from '@/entities'
import { ISmsCodeCheck, ISmsCodeOption } from '@/interface'
import { CoreException, NRedis, SmsExceptionType } from '@/modules'
import { RType } from '@/modules/redis/interface'
import { timestampFormat } from '@/util'
import { Injectable } from '@nestjs/common'
import { SmsAliService } from './sms-ali.service'

@Injectable()
export class SmsService {
    constructor(
        private readonly smsRecordRepo: SmsRecordRepo,
        private readonly redis: NRedis,
        private readonly smsAliService: SmsAliService,
    ) {}

    /**
     * @description: 发送短信验证码
     * @param {ISmsCodeOption} option
     * @return {*}
     */
    public async sendCode(option: ISmsCodeOption) {
        const { phone, validityTime = 600 } = option
        const code = Math.floor(Math.random() * 899999 + 100000).toString()
        const res = await this.smsAliService.sendCode(option, code)
        const now = timestampFormat()
        await this.redis.set(RType.PREFIX_SMS_CODE + phone, code, validityTime)
        await this.smsRecordRepo.save(
            this.smsRecordRepo.create({
                ...res,
                ct: now,
            }),
        )
        delete res.content
        delete res.template
        delete res.sgin
        return res
    }

    /**
     * @description: 校验验证码
     * @param {ISmsCodeCheck} option
     * @return {*}
     */
    public async checkCode(option: ISmsCodeCheck) {
        const { phone, code, consumption = 0 } = option
        const smsCode = await this.redis.get(RType.PREFIX_SMS_CODE + phone)
        if (smsCode && code === smsCode) {
            if (consumption === 1) {
                await this.redis.del(RType.PREFIX_SMS_CODE + phone)
            }
            return { message: '验证成功！' }
        }
        throw new CoreException(SmsExceptionType.ERROR_SMS_CODE_FAIL)
    }
}
